//
//  AddNewAddressController.m
//  ios-supplier
//
//  Created by Benlai on 15/8/4.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "AddNewAddressController.h"
#import "JFBDropdownMenu.h"
#import "JFBRegionDS.h"
#import "JFBStoreInfoDS.h"

@interface AddNewAddressController () <UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *reveiveNameLabel;//姓名
@property (weak, nonatomic) IBOutlet UITextField *receiveMobileLabel;//电话
@property (weak, nonatomic) IBOutlet UIButton *receiveRegionBtn;//所在地区
@property (weak, nonatomic) IBOutlet UITextField *reveiveDetailAddressLabel;//详细地址
@property (weak, nonatomic) IBOutlet UILabel *receiveCityLabel;//所在城市
@property (weak, nonatomic) IBOutlet UILabel *receiveRegionLabel;//所在城区
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;//保存
@property (weak, nonatomic)IBOutlet UILabel *regionLabel;//所在城区:(没用)
@property (assign, nonatomic) NSInteger regionID;
@property (strong, nonatomic) NSMutableArray *regionArray;
- (IBAction)saveBtnPressed:(id)sender;
- (IBAction)selectArea:(id)sender;

@end

@implementation AddNewAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    JFBStoreInfoDS *infoDS = [JFBStoreInfoDS loadFromDB];
    self.receiveCityLabel.text = infoDS.city_name;
    if (self.addressInfo)
    {
//        self.receiveCityLabel.text = self.addressInfo.city_name;
        self.reveiveNameLabel.text = self.addressInfo.receiver;
        self.receiveMobileLabel.text = self.addressInfo.receiver_phone;
        [self.receiveRegionBtn setTitle: self.addressInfo.address_name forState: UIControlStateNormal];
        [self.receiveRegionBtn setTitleColor: [UIColor darkGrayColor] forState: UIControlStateNormal];
        self.reveiveDetailAddressLabel.text = self.addressInfo.address_detail;
        self.receiveRegionLabel.text = self.addressInfo.region_name;
        self.regionID = self.addressInfo.regionID;
    }
    [self.saveBtn.layer setCornerRadius: self.saveBtn.frame.size.height / 2];
    self.navigationItem.title = @"新增收货地址";
    self.receiveRegionLabel.userInteractionEnabled = YES;
    [self.receiveRegionLabel addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(receiveRegionLabelDidClicked:)]];
    self.reveiveDetailAddressLabel.delegate = self;
    self.receiveMobileLabel.delegate = self;
    self.receiveMobileLabel.keyboardType = UIKeyboardTypeNumberPad;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
    
    self.regionArray = [@[] mutableCopy];
    [self loadRegionList];
}

//-(void)setAddressInfo:(SelecctAddressDS *)addressInfo
//{
//    _addressInfo = addressInfo;
//    
//}
-(void)loadRegionList
{
    JFBStoreInfoDS *infoDS = [JFBStoreInfoDS loadFromDB];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"city_id"] = infoDS.city_id;
    params[@"shop_id"] = [NSNumber numberWithInteger: infoDS.ID];
    params[@"ut"] = [JFBGlobalSetting getSetting].defaultAnyCode;
    
    [[JFBAPIClient sharedClient:false] GET:@"/shop/purchase/address/region.json" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        [self.regionArray removeAllObjects];
        
        NSArray *regionArray = responseObject[@"data"];
        
        int i = 0;
        for (NSDictionary *regionDict in regionArray) {
            JFBRegionDS *regionDs = [[JFBRegionDS alloc]initWithAttributes:regionDict];
            [self.regionArray addObject:regionDs];
            
            if (i == 0 && !self.addressInfo.region_name)
            {
                self.receiveRegionLabel.text = regionDs.name;
                self.regionID = regionDs.ID;
            }
            if (i == 0 && !self.addressInfo) // 编辑收货地址时，区默认显示第一个区
            {
                self.receiveRegionLabel.text = regionDs.name;
                self.regionID = regionDs.ID;
            }
            i++;
        }
        
        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.receiveMobileLabel) {
        if (string.length == 0) return YES;
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

 // 选择城区列表
-(void)receiveRegionLabelDidClicked:(UITapGestureRecognizer *)recognuzer
{
    //1.创建下拉菜单
    JFBDropdownMenu *menu = [JFBDropdownMenu menu];
    RegionMenuController *dropDownMenu = [[RegionMenuController alloc] init ];
    dropDownMenu.regionArray = self.regionArray;
    dropDownMenu.delegate = self;
    CGRect frame = [self.receiveRegionLabel convertRect:self.receiveRegionLabel.frame toView: self.view];
    dropDownMenu.view.height = (self.view.frame.size.height) - (CGRectGetMaxY(frame) + 5);
    dropDownMenu.view.width = (self.view.width) - (self.regionLabel.width)  + 30;
    menu.contentController = dropDownMenu;
    [menu showFrom:self.receiveRegionLabel];
}

- (IBAction)saveBtnPressed:(id)sender
{
    if ([NSString isNilOrEmptyOrWhitespace:self.reveiveNameLabel.text])
    {
        [JFBUIAnimation errorInputTips:self.reveiveNameLabel animation:TipsBounces];
        [JFBUIAnimation alertTips: @"姓名不能为空"];
        return;
    }
    if ([NSString isNilOrEmptyOrWhitespace:self.receiveMobileLabel.text] )
    {
        [JFBUIAnimation errorInputTips:self.receiveMobileLabel animation:TipsBounces];
        
        [JFBUIAnimation alertTips: @"电话号码不能为空"];
        return;
    }
    if ([NSString isNilOrEmptyOrWhitespace:self.receiveRegionBtn.titleLabel.text])
    {
        [JFBUIAnimation errorInputTips:self.receiveRegionBtn animation:TipsBounces];
        [JFBUIAnimation alertTips: @"所在地区不能为空"];
        return;
    }
    if ([NSString isNilOrEmptyOrWhitespace:self.reveiveDetailAddressLabel.text])
    {
        [JFBUIAnimation errorInputTips:self.reveiveDetailAddressLabel animation:TipsBounces];
        [JFBUIAnimation alertTips: @"详细地址不能为空"];
        return;
    }
    if (![self.receiveMobileLabel.text isValidMobileNumber])
    {
        [JFBUIAnimation errorInputTips:self.receiveMobileLabel animation:TipsBounces];
        [JFBUIAnimation alertTips: @"电话号码不合法"];
        return;
    }
    SelecctAddressDS *newAddress = [[SelecctAddressDS alloc] init];
    newAddress.receiver = self.reveiveNameLabel.text;
    newAddress.receiver_phone = self.receiveMobileLabel.text;
    newAddress.address_name = [self.receiveRegionBtn titleForState: UIControlStateNormal];
    newAddress.address_detail = self.reveiveDetailAddressLabel.text;
    newAddress.regionID = self.regionID;
    
    if (self.addressInfo)
    {
        newAddress.ID = self.addressInfo.ID;
        [SelecctAddressDS updateReceiveAddress:^(BOOL isSuccess, NSString *message, NSError *error) {
            [JFBUIAnimation alertTips:message];
            [self.delegate sendAddressInfo:newAddress];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:3]  animated:YES];
        } receiveAddress: newAddress];
    }
    else
    {
        [SelecctAddressDS addReceiveAddress:^(BOOL isSuccess, NSString *message, NSError *error) {
            [JFBUIAnimation alertTips:message];
            [self.delegate sendAddressInfo:newAddress];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:3]  animated:YES];
            
        } receiveAddress: newAddress];
    }
}

- (IBAction)selectArea:(id)sender
{
    ReceivingAddressController *receivingAddressController = [[ReceivingAddressController alloc]init];
    receivingAddressController.delegate = self;
    [self.navigationController pushViewController:receivingAddressController animated: YES];
}

-(void)selectedRegion:(NSString *)region
{
    [self.receiveRegionBtn setTitle: region forState:UIControlStateNormal];
    [self.receiveRegionBtn setTitleColor: [UIColor darkGrayColor] forState:UIControlStateNormal];
}

-(void)setleceiveRegion:(NSString *)str withRegionId:(NSInteger)reginID
{
    _receiveRegionLabel.text = str;
    self.regionID = reginID;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame=CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height);
    return YES;
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect addStockRect = [textField convertRect: textField.frame toView: self.view];
    CGFloat offSet = self.view.frame.size.height - (CGRectGetMaxY(addStockRect) + 216 + 40);
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    if(offSet < 0)
    {
        self.view.frame=CGRectMake(0, offSet,self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.reveiveNameLabel resignFirstResponder];
    [self.receiveMobileLabel resignFirstResponder];
    [self.reveiveDetailAddressLabel resignFirstResponder];
}
@end
